<template>
    <div id="app">
        <keep-alive>
            <router-view v-if="$route.meta.keepAlive" />
        </keep-alive>
        <router-view v-if="!$route.meta.keepAlive" />
    </div>
</template>

<script>
import VConsole from 'vconsole';
import bus from './utils/eventBus.js';
import { getCurrentInstance } from 'vue';

export default {
    name: 'App',
    onBeforeMount() {
        // 初始化
        this.JSBridge.init();
        this.JSBridge.registerHandler('toast', (data, responseHandler) => {
            this.$toast(data || 'What up?');
            responseHandler('JS Callback');
        });
        // 注册消息监听
        bus.on('tdy-relogin', () => {
            if (window.isClient) {
                this.JSBridge.callHandler('clearLogin');
            } else if (window.isWX) {
                wx.miniProgram.navigateBack();
            } else {
                this.$router.push('/download');
            }
        });

        // 客户端或小程序挂载开发者工具
        if (process.env.NODE_ENV !== 'production' && (window.isClient || window.isWX)) {
            new VConsole({ disableLogScrolling: false, defaultPlugins: ['system', 'network'], maxLogNumber: 200 });
        }
        // 检测是否客户端
        if (window.isClient) {
            // 尝试获得版本号
            this.JSBridge.callHandler('getVersion', null, function (code) {
                window._appCode = ~~code;
                console.log('getVersion:', window._appCode);
            });
            this.JSBridge.callHandler('getVersionCode', null, function (code) {
                window._appCode = ~~code;
                console.log('getVersionCode:', window._appCode);
            });
            // 尝试获取并写入登录信息
            this.JSBridge.callHandler('getAuthorization', null, (token) => {
                console.log('app get token:', token);
                this.HTTP.setAuth(token);
            });
            if (window.isIOS) {
                // 兼容iOS 处理token获取
                const ua = navigator.userAgent;
                const token = ua.substr(ua.indexOf('TOKEN/') + 6, 32);
                console.log('ios get token:', token);
                this.HTTP.setAuth(token);
            } else if (window.isAndroid && window['tdy']) {
                // 兼容安卓 提供同步函数 处理获取延迟问题
                this.HTTP.setAuth(window.tdy.getToken());
            }
        } else {
            const token = this.$route.query.token;
            if (typeof token === 'string' && token.length === 32) {
                this.HTTP.setAuth(token);
            } else {
                // WEB写入登录信息
                this.HTTP.setAuth('ed4ad41fed39450b8c84d0dd428fdb7e'); // android
            }
        }
        console.log('window.isClient:', window.isClient);
    }
};
</script>
